package iconcurrent;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author or2
 * @date 2021/7/14 22:56
 */
public class IThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public IThreadFactory(Class<?> clazz) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        String clazzName = clazz.getName();
        String name = clazzName;
        if (clazzName.length() > 8) {
            String[] split = clazzName.split("\\.");
            name = split[split.length - 1];
        }
        namePrefix = name + "[" +
                poolNumber.getAndIncrement() +
                "]Ξ线程";
    }

    /**
     * 根据给的字符串名称创建线程
     *
     * @param name 线程名称
     */
    public IThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        namePrefix = name + "[" +
                poolNumber.getAndIncrement() +
                "]Ξ线程";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}
